import { instantiate, Node, Prefab } from "cc";
import { SingletonClass } from "../Frame/Script/core/singletonClass";
import { PlatformManager } from "../Frame/Script/core/platformManager";
import { EventManager } from "../Frame/Script/core/eventManager";
import TimeManager from "../Frame/Script/core/timeManager";
import { Net } from "../Frame/Script/net/net";
import GameData from "./core/GameData";
import { UserInfo } from "./core/UserInfo";
import { ViewManager } from "../Frame/Script/core/viewManager";
import { Http } from "./network/http";
import { ws } from "./network/wsClient";
import { NetInfo } from "./core/NetInfo";
import { MsgGamePlaying } from "./network/net_proto/protocols/game/MsgGamePlaying";
import { MsgClearLine } from "./network/net_proto/protocols/game/MsgClearLine";
import { MsgSink } from "./network/net_proto/protocols/game/MsgSink";
import { MsgGameOver } from "./network/net_proto/protocols/game/MsgGameOver";
import { EventName } from "../Frame/Script/const/eventName";
import { MsgStartGame } from "./network/net_proto/protocols/game/MsgStartGame";
import { MsgJoinOrLeaveLivingRoom } from "./network/net_proto/protocols/game/MsgJoinOrLeaveLivingRoom";
import { MsgJoinOrLeaveSeat } from "./network/net_proto/protocols/game/MsgJoinOrLeaveSeat";
import { MsgReadyOrNot } from "./network/net_proto/protocols/game/MsgReadyOrNot";
import { MsgSelectModel } from "./network/net_proto/protocols/game/MsgSelectModel";
import { ViewName } from "../Frame/Script/const/viewNameConst";
import { GameModeCmd } from "./network/net_proto/protocols/commonRoom";
import { MsgComeUp } from "./network/net_proto/protocols/game/MsgComeUp";
import { Native_Operation } from "../Frame/Script/platform/nativePlatform";
import { FrameVoiceMgr } from "../Frame/Script/Manager/FrameVoiceMgr";

/**
 * App管理
 */
class GameApp extends SingletonClass<GameApp> {

    private canvas: Node;

    get platform() { return PlatformManager.getInstance<PlatformManager>(PlatformManager); }
    get event() { return EventManager.getInstance<EventManager>(EventManager); }
    get view() { return ViewManager.getInstance<ViewManager>(ViewManager); }
    get timer() { return TimeManager.getInstance<TimeManager>(TimeManager); }
    get gameData() { return GameData.getInstance<GameData>(GameData); }
    get user() { return UserInfo.getInstance<UserInfo>(UserInfo); }
    get net() { return Net }
    get ws() { return ws }
    get audio() { return FrameVoiceMgr.instance }

    protected async onInit(canvas: Node) {
        this.canvas = canvas;
        this.view.init(this.canvas);
        this.platform.init();
        this.timer.init();
        this.gameData.init();
        this.audio.init();
        // this.user.init();
        this.initSelfUserInfo();
        // this.net.init();
        // this.initHttp();
    }

    public async initHttp() {
        const ret = await Http.sendJson(
            "http://119.45.7.202:3000/login/LoginByDYin",
            {
                openId: "id-" + App.user.id,
                name: App.user.name,
                icon: App.user.avatar_url,
                session: ""
            },
            true
        );
        const wsUrl = ret["res"]["gameUrl"];
        const token = ret["res"]["token"];
        NetInfo.token = token;
        let result = await ws.init(wsUrl);
        if (result) {
            let msg = await ws.callApi("login/LoginGame", { token: token, session: "" });
            if (msg.isSucc) {
                NetInfo.session = msg.res.session;
                NetInfo.uid = msg.res.uid;
                this.addGameListener();
                this.JoinRoom();
            } else {
                console.error(msg.err);
            }
        }
    }

    private initSelfUserInfo() {
        this.platform.sendNativeMsg(Native_Operation.show_as_view, "0");
        this.platform.sendNativeMsg(Native_Operation.UserInfo, "");
    }

    /**
     * 添加全局监听
     */
    private addGameListener() {
        ws.listenMsg("game/JoinOrLeaveLivingRoom", (data: MsgJoinOrLeaveLivingRoom) => {
            App.event.emit(EventName.Game.JOIN_OR_LEAVE_ROOM, data);
        })
        ws.listenMsg("game/JoinOrLeaveSeat", (data: MsgJoinOrLeaveSeat) => {
            App.event.emit(EventName.Game.JOIN_OR_LEAVE_SEAT, data);
        })
        ws.listenMsg("game/ReadyOrNot", (data: MsgReadyOrNot) => {
            App.event.emit(EventName.Game.READY_OR_NOT, data);
        })
        ws.listenMsg("game/SelectModel", (data: MsgSelectModel) => {
            App.event.emit(EventName.Game.SElECT_MODEL, data);
        })
        ws.listenMsg("game/StartGame", (data: MsgStartGame) => {
            App.event.emit(EventName.Game.START_GAME, data);
        })
        ws.listenMsg("game/GamePlaying", (data: MsgGamePlaying) => {
            App.event.emit(EventName.Game.GAME_PLAYING, data);
        });
        ws.listenMsg("game/ClearLine", (data: MsgClearLine) => {
            App.event.emit(EventName.Game.CLEAR_LINE, data);
        });
        ws.listenMsg("game/ComeUp", (data: MsgComeUp) => {
            App.event.emit(EventName.Game.COME_UP, data);
        })
        ws.listenMsg("game/Sink", (data: MsgSink) => {
            App.event.emit(EventName.Game.SINK, data);
        });
        ws.listenMsg("game/GameOver", (data: MsgGameOver) => {
            App.event.emit(EventName.Game.GAME_OVER, data);
        });
    }

    private async JoinRoom() {
        console.log("JoinRoom-" + App.user.roomId);
        let msg = await App.ws.callApi("game/JoinLivingRoom", {
            roomId: App.user.roomId,
            session: NetInfo.session
        })
        console.log("ResJoinLivingRoom=>", msg);
        if (msg && msg.isSucc) {
            let roomData = msg.res.livingRoom;
            if (roomData.game) {
                let num = 0;
                let seats = roomData.seats;
                seats.forEach(p => { if (p.user) num += 1; });
                App.gameData.setGameSeats(seats);
                App.gameData.setPeopleNum(num);
                App.gameData.setModelData(roomData.model);
                App.gameData.setTypeData(roomData.subModel);
                if (roomData.model === GameModeCmd.合作模式) {
                    App.view.openView(ViewName.Single.eModel1View);
                } else if (roomData.model === GameModeCmd.对抗模式) {
                    App.view.openView(ViewName.Single.eModel2View);
                } else {
                    console.error("game model err:", roomData.model);
                }
            } else {
                App.view.openView(ViewName.Single.eHomeView, roomData);
            }
        } else {
            console.error("加入房间失败");
        }
    }


    //窗口大小变化监听
    evtResizeCallback() {

    }
}

export const App: GameApp = GameApp.getInstance<GameApp>(GameApp);



